<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Home\Model;
use Think\Model;
use User\Api\UserApi;

/**
 * 文档基础模型
 */
class StudentModel extends Model{
	
    /**
     * 登录指定用户
     * @param  integer $id 用户ID
     * @return boolean      ture-登录成功，false-登录失败
     */
    public function login($id){
        /* 检测是否在当前应用注册 */
    	$user = $this->field(true)->find($id);
        if(!$user || 1 != $user['status']) {
            $this->error = '用户未激活或已禁用！'; //应用级别禁用
            return false;
        }
		
        /* 登录用户 */
        $this->autoLogin($user);

        //记录行为
        //action_log('user_login', 'student', $uid, $uid);

        return true;
    }

    /**
     * 注销当前用户
     * @return void
     */
    public function logout(){
        session('user_auth', null);
        session('user_auth_sign', null);
    }

    /**
     * 自动登录用户
     * @param  integer $user 用户信息数组
     */
    private function autoLogin($user){
		$class  =  M('ClassInfo')->find($user['classid']);
        $auth   = array(
        	'uid'				=>$user['id'],//common.function.php中验证是否登陆，验证的字段为uid
        	'schoolid'			=>$user['schoolid'],
        	'schoolname'		=>$user['schoolname'],
        	'school_short_name' =>substr($user['sno'],0,4),
        	'classid'			=>$user['classid'],
        	'class_sno'         =>$class['class_sno'],
            'username'			=>$user['username'],
        	'picture'           =>$user['picture'],
        	'score'             =>$user['score'],
        	'book_page'         =>$user['book_page'],
        	'have_read_count'   =>$user['have_read_count'],	
        	'sno'				=>$user['sno'],
        );
        session('user_auth', $auth);
        session('user_auth_sign', data_auth_sign($auth));

    }
    /**
     * 学生点击开始阅读
     * @param $bookgameid  读书比赛ID
     * @param $booklistid  学生读书比赛与书目关系表ID
     * @return boolean     返回true或false
     *   */
    public function startRead($bookgameid,$booklistid){
    	//先判断比赛是不是开始着的
    	if(!$this->judge($bookgameid)){
    		$this->error = '读书比赛已经结束！';
    		return false;
    	}
    	$booklistGameRelation    =  M('BooklistGameRelation');
    	$booklistGameRelationRst =  $booklistGameRelation->find($booklistid);
    	$booklistGameRelationRst['start_time']    =  time();
    	$booklistGameRelationRst['isready']       =  2;
    	$rst  =  $booklistGameRelation->save($booklistGameRelationRst);
    	if(!$rst){
    		$this->error = '开始读书失败，请重试！';
    		return false;
    	}else{
    		return true;
    	}
    	
    }
   /*
    * 判断比赛是否开始
    * @param  $bookgameid 读书比赛ID
    * @return boolean     返回true or false
    *   
    *   */
    public function judge($bookgameid){
    	$bookGame        =  M('BookGame');
    	//AR查询
    	$bookGameResult  =  $bookGame->find($bookgameid);
    	//'isready'是否开启（0，表示已结束，1，表示未开始，2表示已开始，默认为1）
    	//此字段由学校管理员控制，开启或者结束本次阅读。
    	//dump($bookGameResult['isready']);
    	if( $bookGameResult['isready'] != 2){
    		$this->error = '当前比赛已经结束!';
    		return false;
    	}else{
    		return true;
    	}
    	
    }
    /**
     * 学生点击结束阅读
     * @param $bookgameid  读书比赛ID
     * @param $bookid      图书ID
     * @param $studentid   学生ID
     * @param $classid     班级ID
     * @param $booklistid  学生读书比赛与书目关系表ID
     * @return boolean     返回true或false
     *   */
    public function endRead($bookgameid,$bookid,$studentid,$classid,$booklistid){
    	//判断比赛是否还是开始的
    	 if(!$this->judge($bookgameid)){
    	 	return false;
    	 }
    	/* 精简版 */
    	M()->startTrans();//开启事务
    	if(!$this->changeStatus($bookgameid,$bookid,$studentid,$classid,$booklistid)){
    		M()->rollback();
    		return false;
    	}
    	M()->commit();
    	
    	return true;
    	
    }
    
    private function changeStatus($bookgameid,$bookid,$studentid,$classid,$booklistid){
    	$map['book_game_id']  =  $bookgameid;
    	$map['bookid']        =  $bookid;
    	$status               =  array(0=>'count_book');
    	//...当前比赛当前书籍已读次数+1
    	//$bookGameStatus       =  M('BookGameStatus');
    	//$bookGameStatusRst    =  $bookGameStatus->where($map)->find();
    	 if(!$this->read('BookGameStatus',$map,$status)){
    		return false;
    	} 
    	//action_log('add_bookgamestatus','book_game_status',$bookGameStatusRst['id'],SID);
    	/* if(action_log('add_bookgamestatus','book_game_status',$bookGameStatusRst['id'],SID)!=''){
    		return false;
    	}   */
    	$rel['book_game_id']  =  $bookgameid;
    	$rel['studentid']     =  $studentid;
    	$relStatus            =  array(0=>'have_read_count',1=>'integral');
    	//...当前比赛的当前学生已读图书本数+1,本次累计积分+1
    	 if(!$this->read('BookGameRelation',$rel,$relStatus)){
    		return false;
    	} 
       /*  $bookgameRelation     =  M('BookGameRelation');
    	$bookgameRelationRst  =  $bookgameRelation->where($rel)->find();
    	action_log('add_bookgamerelation','book_game_relation',$bookgameRelationRst['id'],SID); */
    	/* if(action_log('add_bookgamerelation','book_game_relation',$bookgameRelationRst['id'],SID)!=''){
    		return false;
    	}   */
    	$class['classid']           =  $classid;
    	$class['book_game_id']      =  $bookgameid;
    	$classStatus          =  array(0=>'score');
    	//...当前比赛中当前班级的班级积分+1
    	if(!$this->read('ClassGame',$class,$classStatus)){
    		return false;
    	}
    	$classRelation['classid']  =  $classid;
    	$classRelation['bookid']   =  $bookid;
    	$classRelation['book_game_id']  =  $bookgameid;
    	$classRelationStatus  =  array(0=>'read_times');
    	//当前比赛中当前班级对当前书目已读次数+1
    	if(!$this->read('ClassGameRelation',$classRelation,$classRelationStatus)){
    		return false;
    	}
    	$booklistGameRelationDatas['id']        =  $booklistid;
    	$booklistGameRelationDatas['end_time']  =  time();
    	$booklistGameRelationDatas['isready']   =  0;
    	//当前读书比赛结束，状态修改为0（已结束），并存入当前时间。
    	if(!M('BooklistGameRelation')->save($booklistGameRelationDatas)){
    		$this->error = '学生读书比赛与书目关系修改失败!';
    		return false;
    	}
    	$Student        = M('Student');
    	$bookpage       = M('BookInfo')->find($bookid);
    	$studentInfo    = $Student->find($studentid);
    	$studentInfo['score']            =  $studentInfo['score'] + 1;
    	$studentInfo['have_read_count']  =  $studentInfo['have_read_count'] + 1;
    	$studentInfo['book_page']        =  $studentInfo['book_page'] + $bookpage['book_page'];
    	$studentInfo['level']            =  $this->levelRule($studentInfo['score'],$studentInfo['level']);
    	if(!$Student->save($studentInfo)){
    		$this->error  = '学生信息修改失败，请重试!';
    		return false;
    	}
    	//修改session信息
    	session('user_auth.score',$studentInfo['score']);
    	session('user_auth.have_read_count',$studentInfo['have_read_count']);
    	session('user_auth.book_page',$studentInfo['book_page']);
    	session('user_auth.level',$studentInfo['level']); 
    	session('user_auth_sign', data_auth_sign(session('user_auth')));
    	return true;
    	
    }
    
    /*
     * 积分规则
     * 
     *   */
    public function levelRule($score,$level){
    	if($score == 100 || $score == 1000 || $score == 2000){
    		$level = $level +1;
    	}
    	return $level;
    }
    
   
    private function read($model,$map,$status){
    	$models       =  M($model);
    	//查询为了找主键
    	$modelData   =  $models->where($map)->find();
    	for ($i=0;$i<count($status);$i++){
    		/* if(!is_numeric($modelData[$status[$i]])){
    			$modelData[$status[$i]]  =  0;
    		} */
    		$modelData[$status[$i]]  =  $modelData[$status[$i]]+1;
    	}
    	$modelRst    =  $models->save($modelData);
    	if(!$modelRst){
    		$this->error  =  $model.'修改失败，请重试!';
    		return false;
    	}
    	return true;
    }
    /*
     * 	搜索当前学生的比赛
     *  @param  $isready   比赛是否开始字段
     *  @param  $status    比赛状态
     *  @param  $studentid 学生 ID
     *  @return array      返回当前学生所有比赛信息二维数组
     *   
     *   */
    public function searchBookGame($isready,$status,$studentid){
    	//2表示已经开始的比赛
    	if(is_array($isready)){
    		$map['bg.isready']     = array('in',$isready);
    	}else{
    		$map['bg.isready']     = 2;
    	}
    	$map['bg.status']      = $status;//1表示正常状态
    	$map['bgr.studentid']  = $studentid;//学生ID
    	$bookGameRelation      = M('BooklistGameRelation bgr');
    	$rst      =  $bookGameRelation->join('primary_book_game bg ON bg.id=bgr.book_game_id')
    					              ->join('primary_book_game_relation bgrn ON bgrn.studentid=bgr.studentid and bgrn.book_game_id=bgr.book_game_id')
			    					  ->where($map)
							    	  ->group('book_game_id')
							    	  ->field('bg.*,bgr.book_game_id,bgrn.integral')
							    	  ->select();
    	return $rst;
    }
    /*
     *  搜索比赛书籍详细信息及本班阅读次数
     *  @param $rst         学生读书比赛详细信息
     *  @param $studentid   学生ID
     *  @param $classid     班级ID
     *   */
    public function searchBookGameDetail($rst,$studentid,$classid){
    	$bookGameId            =  array_column($rst, 'book_game_id');
    	$stu['bgr.studentid']  =  $studentid;
    	$stu['cgr.classid']    =  $classid;
    	for($i =0;$i < count($bookGameId); $i++){
    		$stu['bgr.book_game_id']  =  $bookGameId[$i];
    		$booklistGameRelationRst  =  M('BooklistGameRelation bgr')
    		->join('primary_book_info bi ON bi.id=bgr.bookid','LEFT')
    		->join('primary_class_game_relation cgr ON cgr.book_game_id=bgr.book_game_id and cgr.bookid=bgr.bookid')
    		->where($stu)
    		->field('bgr.*,bi.bookname,bi.cover,bi.intro,bi.author,bi.press,bi.book_page,cgr.read_times')
    		->select();
    		$rst[$i]['student_game']  = $booklistGameRelationRst;
    		 
    	}
    	return $rst;
    }
   
}
